<?php

namespace App\Http\Controllers;

use App\Models\Recharge;
use App\Models\Store;
use App\Models\StoreBusinessHours;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class StoreController extends Controller
{
    /**
     * 列表
     * GET /api/store
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $params = $request->all();

        // 门店列表
        $store = new Store();
        $params['status'] = 'NORMAL';
        $data = $store->getList($params);

        // 营业时间
        $storeBusinessHours = new StoreBusinessHours();
        $params['store_ids'] = array_column($data, 'id');
        $business = $storeBusinessHours->getList($params);
        $business = self::groupBy($business, 'store_id');

        foreach ($data as $key => $value) {
            $data[$key]->business = $business[$value->id] ?? [];
        }

        return response()->json(['status' => 1, 'data' => $data]);
    }

    public function cityStore(Request $request): JsonResponse
    {
        $params = $request->all();

        // 门店列表
        $store = new Store();
        $params['status'] = 'NORMAL';
        $data = $store->cityStore($params);

        return response()->json(['status' => 1, 'data' => $data]);
    }

    public static function groupBy($arr, $key_field): array
    {
        $ret = array();
        foreach ($arr as $row) {
            $key = $row->$key_field;
            $ret[$key][] = $row;
        }

        return $ret;
    }
}
